import BookController from '@/services/book';
import { IBook } from '@/types/book';
import { PageContainer } from '@ant-design/pro-components';
import { message } from 'antd';
import React, { useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import BookForm from '../components/BookForm';

const EditBook: React.FC = () => {
  const navigate = useNavigate();
  const { bookId } = useParams();

  // 维护一个状态，该状态用于存储用户输入的书籍信息
  const [bookInfo, setBookInfo] = useState<IBook>({
    bookTitle: '',
    bookIntro: '',
    downloadLink: '',
    requirePoints: '',
    bookPic: '',
    typeId: '',
  } as unknown as IBook);

  /**
   * 确认新增书籍
   */
  function handleSubmit(bookInfo: IBook) {
    if (!bookId) return;
    BookController.editBook(bookId, bookInfo);
    message.success('编辑书籍成功');
    // 跳回书籍列表页面
    navigate('/book/book-list');
  }

  useEffect(() => {
    async function fetchData() {
      if (bookId) {
        const { data } = await BookController.getBookById(bookId);
        setBookInfo(data);
      }
    }
    fetchData();
  }, [bookId]);

  return (
    <PageContainer>
      <div className="container" style={{ width: '1000px' }}>
        <BookForm type="edit" bookInfo={bookInfo} handleSubmit={handleSubmit} />
      </div>
    </PageContainer>
  );
};

export default EditBook;
